﻿ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace T03ChatServer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        //服务端的socket
        private Socket serverSocket = null;
        //服务启动标志：控制启动与停止
        private bool isListen = true;

        //字典保存多个用户的连接信息 key（用户名）value（socket连接）
        public Dictionary<string, Socket> clientList = null;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void BtnStop_Click(object sender, RoutedEventArgs e)
        {
            //监听（accept）也需要新开线程
            if(serverSocket == null){
                isListen = true;
                //初始化集合
                clientList = new Dictionary<string, Socket>();
                //服务器地址：测试使用本地地址：127.0.0.1
                IPAddress ip = IPAddress.Parse("127.0.0.1");
                IPEndPoint iep = new IPEndPoint(ip, 18888);
                //创建socket
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //绑定
                serverSocket.Bind(iep);
                //监听
                serverSocket.Listen(100);
                //启动线程开启服务响应
                Thread t = new Thread(StartListen);
                //后台运行模式
                t.IsBackground = true;
                t.Start();
                //提示信息，异步模式更新UI显示
                TxtMsg.Dispatcher.BeginInvoke(new Action(() => { TxtMsg.Text += "服务器启动....\r\n"; }));
            }
        }

        private void BtnStart_Click(object sender, RoutedEventArgs e)
        {
            if(serverSocket !=null){
                //关闭所有客户端连接
                foreach (var socket in clientList.Values){
                    socket.Close();
                }
                //清空字典
                clientList.Clear();
              serverSocket.Close ();
               serverSocket =null ;
                //停止监听线程
                isListen =false ;
                TxtMsg.Text +="服务停止！\r\n";
             }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            //窗口关闭停止服务
            isListen = false;
            if (serverSocket != null)
                Broadcast.PushMessage("服务器即将关闭","",
                    clientList,Broadcast .SYSTEM_MSG);
            { //关闭所有客户端连接
                foreach (var socket in clientList.Values)
                {
                    socket.Close();
                }
                //清空字典
                clientList.Clear();
                serverSocket.Close();
                serverSocket = null;
            }
        }

        /// <summary>
        /// 该函数是服务端socket监听线程的委托函数
        /// </summary>
        private void StartListen(){
            //创建客户端的套接字
            Socket clientSocket = default(Socket);
            try{
                while (isListen) { 
                //阻塞
                clientSocket = serverSocket.Accept();
                //构建数据缓冲
                byte[] bytesFrom = new byte[4096];
                string dataFromClient = null;
                int len = clientSocket.Receive(bytesFrom);
                if (len > 0){
                    //客户端传来的信息（用户名）
                    dataFromClient = Encoding.UTF8.GetString(bytesFrom, 0, len);
                    //分析协议：“$”表示信息的完整性
                    int sublen = dataFromClient.LastIndexOf("$");
                        if (sublen > -1)
                        { //数据合法
                          //分割，获取有效的数据
                            dataFromClient = dataFromClient.Substring(0, sublen);
                            //用户不存在与当前的集合中
                            if (clientList.ContainsKey(dataFromClient))
                            {
                                //加入字典
                                clientList.Add(dataFromClient, clientSocket);
                                //广播新用户信息
                                Broadcast.PushMessage(dataFromClient + "加入",
                                    dataFromClient, clientList, Broadcast.SYSTEM_MSG);
                                //开启客户端连接线程
                                new HandleClient().StartClient(clientSocket, dataFromClient, clientList); ;
                            }
                            else
                            {
                                //如果已存在用户，向客户端发送提示信息
                                clientSocket.Send(Encoding.UTF8.GetBytes("#" + dataFromClient + "#"));
                            }
                        }
                    }
                }
            }catch (Exception e){
                if(clientSocket  !=null && !clientSocket.Connected){
                    clientSocket.Close();
                    clientSocket = null;
                }
                Debug.WriteLine(e.ToString());
            }
        }


    }
}
